<?php
class ControllerSaleRemitMoney extends Controller {
    private $error = array();

    //打款申请页面
    public function index() {
        $this->load->language('sale/remit_money');
        $this->document->setTitle($this->language->get('heading_title'));
        $this->load->model('sale/remit_money');
        $data['breadcrumbs'] = array();

        $data['breadcrumbs'][] = array(
            'text' => $this->language->get('text_home'),
            'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
        );

        $data['breadcrumbs'][] = array(
            'text' => $this->language->get('heading_title'),
            'href' => $this->url->link('sale/remit_money', 'token=' . $this->session->data['token'], 'SSL')
        );

        $data['show_list'] = $this->url->link('sale/remit_money/showList', 'token=' . $this->session->data['token'] . $url, 'SSL');
        $data['remit_url'] = $this->url->link('sale/remit_money/remit', 'token=' . $this->session->data['token'], 'SSL');
        $data['heading_title'] = $this->language->get('heading_title');
        $data['text_title'] = $this->language->get('text_title');
        $data['header'] = $this->load->controller('common/header');
        $data['column_left'] = $this->load->controller('common/column_left');
        $data['footer'] = $this->load->controller('common/footer');
        $data['token'] = $this->session->data['token'];
        $data['typeList'] = array(//补账户类型
            1 => '个人账号',
            2 => '企业账号',
            3 => '易极付账号',
            //4 => '',//没看懂，暂时关闭。。。
        );
        $this->response->setOutput($this->load->view('sale/remit_money_view.tpl', $data));
    }

    //打款历史记录
    public function showList(){
        $this->load->language('sale/remit_money');
        $this->document->setTitle($this->language->get('heading_title_list'));
        $this->load->model('sale/remit_money');

        if (isset($this->request->get['page'])) {
            $page = $this->request->get['page'];
        } else {
            $page = 1;
        }
        $keywords = trim($this->request->get['keywords']);
        $url = '&keywords='.$keywords;
        $data['filter_keywords'] = $keywords;

        $data['breadcrumbs'] = array();
        $data['breadcrumbs'][] = array(
            'text' => $this->language->get('text_home'),
            'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
        );
        $data['breadcrumbs'][] = array(
            'text' => $this->language->get('heading_title_list'),
            'href' => $this->url->link('sale/remit_money/showList', 'token=' . $this->session->data['token'], 'SSL')
        );

        $filter_data = array(
            'keywords'  => $keywords,
            'start'     => ($page - 1) * $this->config->get('config_limit_admin'),
            'limit'     => $this->config->get('config_limit_admin'),
        );

        $history_infos = $this->model_sale_remit_money->getRemitHistorys($filter_data);
        $attribute_total = $this->model_sale_remit_money->getRemittotal($filter_data);
        $data['history_infos'] = $history_infos;
        $data['cancel'] = $this->url->link('sale/remit_money', 'token=' . $this->session->data['token'], 'SSL');

        $pagination = new Pagination();
        $pagination->total = $attribute_total;
        $pagination->page = $page;
        $pagination->limit = $this->config->get('config_limit_admin');
        $pagination->url = $this->url->link('sale/remit_money/showList', '&token=' . $this->session->data['token'] . $url . '&page={page}', 'SSL');
        $data['pagination'] = $pagination->render();

        $data['results'] = sprintf($this->language->get('text_pagination'), ($attribute_total) ? (($page - 1) * $this->config->get('config_limit_admin')) + 1 : 0, ((($page - 1) * $this->config->get('config_limit_admin')) > ($attribute_total - $this->config->get('config_limit_admin'))) ? $attribute_total : ((($page - 1) * $this->config->get('config_limit_admin')) + $this->config->get('config_limit_admin')), $attribute_total, ceil($attribute_total / $this->config->get('config_limit_admin')));

        $data['heading_title_list'] = $this->language->get('heading_title_list');
        $data['text_title_list'] = $this->language->get('text_title_list');
        $data['header'] = $this->load->controller('common/header');
        $data['column_left'] = $this->load->controller('common/column_left');
        $data['footer'] = $this->load->controller('common/footer');
        $data['token'] = $this->session->data['token'];//补搜索功能
        $data['typeList'] = array(//补账户类型
            1 => '个人账号',
            2 => '企业账号',
            3 => '易极付账号',
            //4 => '',//没看懂，暂时关闭。。。
        );
        $data['statusList'] = array(//补打款状态
            0 => '',
            1 => '<span>处理中</span>',
            2 => '<span style="color:green;">打款成功</span>',
            3 => '<span style="color:red;">打款失败</span>',
            4 => '<span style="color:red;">取消打款</span>',
        );

        $this->response->setOutput($this->load->view('sale/remit_money_list.tpl', $data));
    }

    //补全打款人信息
    public function autoComplete() {
        $json = array();
        if (isset($this->request->get['filter_name'])) {
            $this->load->model('sale/remit_money');
            $filter_data = array(
                'filter_name' => $this->request->get['filter_name'],
                'start'       => 0,
                'limit'       => 10
            );
            $results = $this->model_sale_remit_money->getEmploy($filter_data);
            foreach ($results as $result) {
                $json[] = array(
                    'employ_id'     => $result['employ_id'],
                    'employ_name'   => strip_tags(html_entity_decode($result['employ_name'], ENT_QUOTES, 'UTF-8')),
                    'section'       => $result['section'],
                    'bank_name'     => $result['bank_name'],
                    'card_num'      => $result['card_num'],
                    'type'          => $result['type'],
                );
            }
        }
        $sort_order = array();
        foreach ($json as $key => $value) {
            $sort_order[$key] = $value['employ_name'];
        }
        array_multisort($sort_order, SORT_ASC, $json);
        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    }

    //创建打款url（异常返回错误信息）
    public function remit(){
        $employId = (int)$this->request->post['employ_id'];
        $employName = trim($this->request->post['employ_name']);
        $cardType = (int)$this->request->post['card_type'];
        $cardNum = trim($this->request->post['card_num']);
        $bankName = trim($this->request->post['bank_name']);
        $section = trim($this->request->post['section']);
        $amount = round($this->request->post['amount'], 2);
        $comment = trim($this->request->post['comment']);
        $now = date('Y-m-d H:i:s');
        $employData = array(
            'employ_name' => $employName,
            'section' => $section,
            'bank_name' => $bankName,
            'card_num' => $cardNum,
            'type' => $cardType,
        );
        $this->load->model('sale/remit_money');
        if ($employId < 1) {
            $employData['date_add'] = $now;
            $employId = $this->model_sale_remit_money->addEmploy($employData);//首次付款，添加 remit_info 记录
        }else{
            $employData['date_modify'] = $now;
            $this->model_sale_remit_money->updateEmploy($employId, $employData);//强制更新 remit_info 记录
        }
        $bankCode = $this->_getBankCode($bankName);
        if (false === $bankCode) {
            $json['error'] = "不支持的结算银行。";
        }else{
            $this->load->helper('yijiSignHelper');
            $this->load->helper('dto/qftBatchTransfer.class');
            $this->load->helper('YijipayClient');
            //保存打款申请记录
            $remitInfoHistoryData = array(
                'employ_id' => $employId,
                'card_type' => $cardType,
                'card_num' => $cardNum,
                'bank_code' => $bankCode,
                'amount' => $amount,
                'comment' => $comment,
                'date_add' => $now,
                'user_id' => $this->user->getId(),
                'username' => $this->user->getUserName(),
            );
            $RIPK = $this->model_sale_remit_money->addRemitHistory($remitInfoHistoryData);//保存付款申请记录
            $config = $this->getConfig();
            $objReq = new qftBatchTransfer();
            $objReq->setPartnerId($config['partnerId']);
            $objReq->setpayerUserId($config['partnerId']);
            $objReq->setSignType("MD5");
            $YJFPK = 'BHZ2017YEP'.substr(time(), -10).$RIPK;
            $objReq->setOrderNo($YJFPK);
            $objReq->setMerchOrderNo($YJFPK);
            $objReq->setReturnUrl('http://m.bhz360.com/index.php?route=payment/yiji_yep/ret');//同步返回
            $objReq->setNotifyUrl('http://m.bhz360.com/index.php?route=payment/yiji_yep/not');//异步返回
            switch ($cardType) {
                case '1'://个人账号
                    $payInfo = array(
                        array(
                            'itemMerchOrderNo' => $YJFPK,
                            'money' => $amount,
                            'bankCode' => $bankCode,
                            'bankAccountNo' => $cardNum,
                            'bankAccount' => $employName,
                            'memo' => $comment,
                        ),
                    );
                    $objReq->settoPersonCardList(json_encode($payInfo));
                    break;
                case '2'://公司账号
                    $payInfo = array(
                        array(
                            'itemMerchOrderNo' => $YJFPK,
                            'money' => $amount,
                            'bankCode' => $bankCode,
                            'bankAccountNo' => $cardNum,
                            'bankAccount' => $employName,
                            'memo' => $comment,
                        ),
                    );
                    $objReq->settoBusinessCardList(json_encode($payInfo));
                    break;
                case '3'://易极付账号
                    $payInfo = array(
                        array(
                            'itemMerchOrderNo' => $YJFPK,
                            'payeeUserId' => $cardNum,
                            'outPayeeShopId' => $cardNum,
                            'outPayeeShopName' => $employName,
                            'money' => $amount,
                            'memo' => $comment,
                        ),
                    );
                    $objReq->settoBalanceList(json_encode($payInfo));
                    break;
                case '4'://易极付绑卡（暂时不显示）
                    $payInfo = array(
                        array(
                            'pactNo' => '',
                            'outPayeeShopId' => '',
                            'outPayeeShopName' => '',
                            'itemMerchOrderNo' => $YJFPK,
                            'money' => $amount,
                            'memo' => $comment,
                        ),
                    );
                    $objReq->settoPactNoOrderInfoList(json_encode($payInfo));
                    break;
            }
            $client = new YijiPayClient($config);
            $response = $client->execute($objReq);
            //echo $response;die();
            //保存url到申请记录表
            $this->model_sale_remit_money->updateRemitHistory($RIPK, array('pay_url'=>$response));
            $json = array(
                'success' => true,
                'redirect' => $response,
            );
        }
        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    }

    //支付接口配置
    protected function getConfig(){
        return array(
            'partnerId' => '20161201020011981315', //商户ID
            'md5Key' => 'db3d0a81a79b6832c439bbf5ec92b77c', //商户Key
            
            'gatewayUrl' => "https://api.yiji.com/gateway.html", //生产环境
            // 'gatewayUrl' => "https://openapi.yijifu.net/gateway.html"    //测试环境
        );
    }

    //支付接口支持的银行列表
    protected function _getBankCode($bankName){
        $bankList = array(
            '中国农业银行'       => 'ABC',
            '中国银行'           => 'BOC',
            '交通银行'           => 'COMM',
            '中国建设银行'       => 'CCB',
            '中国光大银行'       => 'CEB',
            '兴业银行'           => 'CIB',
            '招商银行'           => 'CMB',
            '民生银行'           => 'CMBC',
            '中信银行'           => 'CITIC',
            '重庆农村商业银行'   => 'CQRCB',
            '中国工商银行'       => 'ICBC',
            '中国邮政储蓄银行'   => 'PSBC',
            '浦发银行'           => 'SPDB',
            '中国银联'           => 'UNION',
            '重庆银行'           => 'CQCB',
            '广东发展银行'       => 'CGB',
            '深圳发展银行'       => 'SDB',
            '华夏银行'           => 'HXB',
            '重庆三峡银行'       => 'CQTGB',
            '平安银行'           => 'PINGANBK',
            '上海银行'           => 'BKSH',
        );
        if (array_key_exists($bankName, $bankList)) {
            return $bankList[$bankName];
        }
        return false;
    }
}
